import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      redirect: '/admin',
      children: [
        {
        path:'/admin',
        name:"admin",
        component: () => import('../views/admin.vue')
        },
        {
          path:'/deliverGoods',
          name:"deliverGoods",
          component: () => import('../views/deliverGoods.vue')
        },
        {
          path:'/comclass',
          name:"comclass",
          component: () => import('../views/fenlei.vue')
        },
        {
          path:'/goods',
          name:"goods",
          component: () => import('../views/goods.vue')
        },
        {
          path:'/banner',
          name:"banner",
          component: () => import('../views/banner.vue')
        },
      ],
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/register.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login.vue')
    },
    {
      path: '/analyse',
      name: 'analyse',
      component: () => import('../views/analyse.vue')
    },
  ]
})
router.beforeEach((to,from,next)=>{
  const token = window.localStorage.getItem('d_token');
  if(to.name !=='login' && to.name !=='register'){//如果不是登录与注册页面
		if(token){next()} //如果已经登录就跳转
		else next({name:'login'}) //否则跳转到登录页面
	}else{
		if(token) next({name:'home'}) //已经登录就跳转到首页
		else next() //否则跳转到登录页面
	}
  // 动态添加路由
  router.addRoute(
    "home",
    {
      path:'/user',
      name:"user",
      component: () => import('../views/user.vue')
    }
  )
})
export default router
